//
// Created by gg on 2023/11/8.
//
#include "UPRE_Bsp_CAN.h"

void CAN_Object::CAN_Init(CAN_HandleTypeDef *hcan) {

    __HAL_CAN_ENABLE_IT(hcan, CAN_IT_RX_FIFO0_MSG_PENDING);
    __HAL_CAN_ENABLE_IT(hcan, CAN_IT_RX_FIFO1_MSG_PENDING);
    this->hcan = hcan;
}

void CAN_FilterInit(CAN_HandleTypeDef *hcan)
{
    CAN_FilterTypeDef		CAN_FilterConfigStructure;

    /*filter config for can2*/
    CAN_FilterConfigStructure.FilterBank = 0;                      // filter 0
    CAN_FilterConfigStructure.FilterMode = CAN_FILTERMODE_IDMASK;  // mask mode
    CAN_FilterConfigStructure.FilterScale = CAN_FILTERSCALE_32BIT;
    CAN_FilterConfigStructure.FilterIdHigh = 0x0000;
    CAN_FilterConfigStructure.FilterIdLow = 0x0000;
    CAN_FilterConfigStructure.FilterMaskIdHigh = 0x0000;
    CAN_FilterConfigStructure.FilterMaskIdLow = 0x0000;          // set mask 0 to receive all can id
    CAN_FilterConfigStructure.FilterFIFOAssignment = CAN_RX_FIFO0; // assign to fifo0
    CAN_FilterConfigStructure.FilterActivation = ENABLE;           // enable can filter
    CAN_FilterConfigStructure.SlaveStartFilterBank = 14;           // only meaningful in dual can mode

    if (HAL_CAN_ConfigFilter(hcan, &CAN_FilterConfigStructure) != HAL_OK)
    {
        Error_Handler();
    }
    /* Start the CAN peripheral */
    if (HAL_CAN_Start(hcan) != HAL_OK)
    {
        /* Start Error */
        Error_Handler();
    }

    /* Activate CAN RX notification */
    if (HAL_CAN_ActivateNotification(hcan, CAN_IT_RX_FIFO0_MSG_PENDING) != HAL_OK)
    {
        /* Notification Error */
        Error_Handler();
    }

}

uint8_t CAN_Object::CAN_Send_Data()
{
    uint32_t TxMailboxX = CAN_TX_MAILBOX0;
    //检测传参是否正确
    assert_param(hcan != NULL);

    TxHeader.ExtId = 0;
    TxHeader.IDE = CAN_ID_STD;
    TxHeader.RTR = CAN_RTR_DATA;
    TxHeader.DLC = 8;
    TxHeader.TransmitGlobalTime = DISABLE;

    //找到空的发送邮箱 把数据发送出去
    while (HAL_CAN_GetTxMailboxesFreeLevel(hcan) == 0);	// 如果三个发送邮箱都阻塞了就等待直到其中某个邮箱空闲
    if ((hcan->Instance->TSR & CAN_TSR_TME0) != RESET) {
        // 检查发送邮箱0状态 如果邮箱0空闲就将待发送数据放入FIFO0
        TxMailboxX = CAN_TX_MAILBOX0;
    } else if ((hcan->Instance->TSR & CAN_TSR_TME1) != RESET) {
        TxMailboxX = CAN_TX_MAILBOX1;
    } else if ((hcan->Instance->TSR & CAN_TSR_TME2) != RESET) {
        TxMailboxX = CAN_TX_MAILBOX2;
    }
    return HAL_CAN_AddTxMessage(hcan, &TxHeader, Tx_Data, &TxMailboxX);
}